package com.adcc.loadsheet.monitor.congifuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@ConfigurationProperties(prefix = "spring.datasource.mysql")
@MapperScan(basePackages = "com.adcc.loadsheet.monitor.mapper.mysql", sqlSessionTemplateRef = "mysqlSqlSessionTemplate")
public class MysqlDataSourceConfiguration {

    // 数据库驱动类名
    private String driverClassName;

    // 数据库url地址
    private String url;

    // 用户名
    private String username;

    // 密码
    private String password;

    // Druid连接池配置
    private DruidProperties druid;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public DruidProperties getDruid() {
        return druid;
    }

    public void setDruid(DruidProperties druid) {
        this.druid = druid;
    }

    @Primary
    @Bean(name = "mysqlDataSource")
    @Qualifier("mysqlDataSource")
    public DataSource oracleMasterDataSource() {
        DruidDataSource dds = new DruidDataSource();
        // 配置基本属性
        dds.setDriverClassName(driverClassName);
        dds.setUsername(username);
        dds.setPassword(password);
        dds.setUrl(url);
        //初始化时建立物理连接的个数
        dds.setInitialSize(druid.getInitialSize());
        //最大连接池数量
        dds.setMaxActive(druid.getMaxActive());
        //最小连接池数量
        dds.setMinIdle(druid.getMinIdle());
        //获取连接池中连接最大等待时长
        dds.setMaxWait(druid.getMaxWait());
        //用来检测连接是否有效的sql
        dds.setValidationQuery(druid.getValidationQuery());
        //设置检测连接的超时时间
        dds.setValidationQueryTimeout(druid.getValidationQueryTimeout());
        //设置查询超时时间
        dds.setQueryTimeout(druid.getQueryTimeout());
        //建议配置为true，不影响性能，并且保证安全性。
        dds.setTestWhileIdle(druid.isTestWhileIdle());
        //建议配置为true 默认自动提交
        dds.setDefaultAutoCommit(druid.isDefaultAutoCommit());
        //JDBC连接池属性（设置数据库的connection timeout 和 socket timeout）
        dds.setConnectionProperties(druid.getConnectionProperties());
        // 一个连接在池中最小生存的时间 unit: ms
        // 当连接池空闲时，池中的minIdle数量以内的连接，空闲时间超过minEvictableIdleTimeMillis，则会执行keepAlive操作
        dds.setMinEvictableIdleTimeMillis(druid.getMinEvictableIdleTimeMillis());
        // 验证连接有效性
        dds.setKeepAlive(druid.isKeepAlive());
        return dds;
    }

    @Primary
    @Bean(name = "mysqlSqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mysql/*.xml"));
        //分页插件
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        p.setProperty("helperDialect", "mysql");
        pageHelper.setProperties(p);
        bean.setPlugins(new Interceptor[] {pageHelper});
        return bean.getObject();
    }

    //配置声明式事务管理器
    @Primary
    @Bean(name = "mysqlTransactionManager")
    public PlatformTransactionManager primaryTransactionManager(@Qualifier("mysqlDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "mysqlSqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
